package com.fss.shop.controller;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyuncs.exceptions.ClientException;
import com.fss.article.domain.Response;
import com.fss.common.core.controller.BaseController;

import com.fss.home.domain.Product;
import com.fss.shop.domain.Shop;
import com.fss.shop.service.ShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.*;


@RestController
@RequestMapping("/shop")
public class ShopController extends BaseController
{
    @Autowired
    private ShopService shopService;

    @GetMapping("/getShopByUserId/{userId}")
    public Shop getShopByUserId(@PathVariable("userId") Long userId) {
        System.out.println("User ID: " + userId);
        Shop shop = shopService.findShopByUserId(userId);
        return shop;
    }
    /**
     * 获取店铺的商品列表
     * @param shopId 店铺ID
     * @return 商品列表
     */
    @GetMapping("/getShopProducts/{shopId}")
    public List<Product> getShopProducts(
            @PathVariable Long shopId,
            @RequestParam(required = false) Integer sortIndex,
            @RequestParam(required = false) Double priceMin,
            @RequestParam(required = false) Double priceMax
    ) {
        System.out.println("Shop ID: " + shopId);
        return shopService.getProductsByShopId(shopId, sortIndex, priceMin, priceMax);
    }
    // 新建店铺接口
    @PostMapping("/create")
    public String createShop(@RequestBody Shop shop) {
        int result = shopService.createShop(shop);
        if (result > 0) {
            return "店铺创建成功";
        } else {
            return "店铺创建失败";
        }
    }
    // 更新店铺信息
    @PostMapping("/update")
    public String updateShop(@RequestBody Shop shop) {
        boolean success = shopService.updateShop(shop);
        return success ? "更新成功" : "更新失败";
    }
    //上传图片
    @PostMapping("/upload")
    public Response uploadImage(@RequestParam("file") MultipartFile file) throws IOException, ClientException {
        String endpoint = "https://oss-cn-guangzhou.aliyuncs.com";
        String bucketName = generateUniqueBucketName("demo");
        // 替换为您的 Bucket 区域
        String region = "cn-guangzhou";
        // 创建 OSSClient 实例
        EnvironmentVariableCredentialsProvider credentialsProvider =
                CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .region(region)
                .build();

        // 1. 创建存储空间（Bucket）
        ossClient.createBucket(bucketName);
        String name= UUID.randomUUID().toString()+".jpg";
        ossClient.putObject(bucketName, name, new ByteArrayInputStream(file.getBytes()));
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, name, HttpMethod.GET);
        Date expiration = new Date(new Date().getTime() + 2*30*24*3600 * 1000L);
        // 通过HTTP GET请求生成签名URL。
        request.setExpiration(expiration);
        URL signedUrl = ossClient.generatePresignedUrl(request);
        // 打印签名URL。
        System.out.println("signed url for getObject: " + signedUrl);
        ossClient.shutdown();


        return new Response(true,signedUrl.toString() );
    }
    public static String generateUniqueBucketName(String prefix) {
        // 获取当前时间戳
        String timestamp = String.valueOf(System.currentTimeMillis());
        // 生成一个 0 到 9999 之间的随机数
        Random random = new Random();
        int randomNum = random.nextInt(10000); // 生成一个 0 到 9999 之间的随机数
        // 连接以形成一个唯一的 Bucket 名称
        return prefix + "-" + timestamp + "-" + randomNum;
    }

}
